package cn.sh.ideal.yedis.builder;

import java.util.concurrent.TimeUnit;

import cn.sh.ideal.yedis.util.Assert;
import cn.sh.ideal.yedis.util.StringUtil;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 构造redis单机的builder；
 *
 * @author: lingguo
 * @time: 2014/9/23 17:42
 */
public class RedisStandaloneBuilder extends BaseBuilder<JedisPool>{
	
	public RedisStandaloneBuilder() {}
	
	public RedisStandaloneBuilder(String host) {
		this.nodeStr = host;
	}
	
	public RedisStandaloneBuilder(String host,JedisPoolConfig poolConfig) {
		this.poolConfig = poolConfig;
		this.nodeStr = host;
	}
	

	public JedisPool build() {
		if (pool == null) {
			while (true) {
				try {
					LOCK.tryLock(100, TimeUnit.MILLISECONDS);
					if (pool == null) {
						Assert.notEmpty(nodeStr,"host info must not be null");
						String[] instanceArr = nodeStr.split(SEPERATOR_IP_PROT);
						Assert.hasLength(instanceArr,2,"host info is invalid");
						if (StringUtil.isEmpty(password)) {
							pool = new JedisPool(poolConfig, instanceArr[0], Integer.valueOf(instanceArr[1]), timeout);
						} else {
							pool = new JedisPool(poolConfig, instanceArr[0], Integer.valueOf(instanceArr[1]), timeout, password);
						}

						return pool;
					}
				} catch (Exception e) {
					logger.error("error in build().", e);
					break;
				}
			}
		}
		return pool;
	}

}
